<template>
  <div>
    <el-card>
      <el-row :gutter="25">
        <el-col :span="10">
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table style="margin-top: 25px" :data="userList" border stripe>
        <!--        索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="头像" prop="userUrl">
          <template slot-scope="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="scope.row.userUrl"
              fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" prop="role">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.role == 1">超级管理者</el-tag>
            <el-tag type="warning" v-if="scope.row.role == 2">管理者</el-tag>
            <el-tag type="info" v-if="scope.row.role == 3">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state">
          <!-- scope.row 就是当前行的信息 作用槽 -->
          <template slot-scope="scope" v-if="user.role != scope.row.role">
            <el-switch v-model="scope.row.state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope" v-if="user.role != scope.row.role">
            <!--            修改-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!--            删除-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <el-dropdown trigger="click" @command="handleCommand" style="margin-left: 10px">
              <span class="el-dropdown-link">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="updateId(scope.row.id)"></el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="2" v-if="scope.row.role != '2'">管理员</el-dropdown-item>
                <el-dropdown-item command="3" v-if="scope.row.role != '3'">普通用户</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

          </template>
        </el-table-column>
      </el-table>
      <!--      分页 size-change 每页最大化 current-change 当前最大化 layout 功能组件-->
      <div style="margin-top: 15px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[1, 2, 5, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%"
               @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addRules"
               ref="addFormRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" :show-password="true"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="userUrl">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9000/eduoss/imgFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>


      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%"
               @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="editRules"
               ref="editFormRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="editForm.password" :show-password="true"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="userUrl">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9000/eduoss/imgFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess1"
            :before-upload="beforeAvatarUpload1">
            <img v-if="imageUrlU" :src="imageUrlU" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserList',
  data() {
    return {
      user: {},
      //查询信息实体
      queryInfo: {
        query: '',
        pageNum: 1, //当前页
        pageSize: 5 //每页最大数
      },
      userList: [],
      total: 0, //总记录数
      addDialogVisible: false,  //对话框
      addForm: {
        username: '',
        password: '',
        email: ''
      },
      imageUrl: '',
      editForm: {},
      imageUrlU: '',
      editRoleId: 0,
      editDialogVisible: false,
      //验证对象
      addRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 10,
            message: '长度在 6 到 10 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '请输入正确邮箱地址',
            trigger: 'blur'
          }
        ]
      },
      editRules: {
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 10,
            message: '长度在 6 到 10 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '请输入正确邮箱地址',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  created() {
    this.getUser()
    this.getUserList();
  },
  methods: {
    getUser() {
      let user = JSON.parse(window.sessionStorage.getItem('user') || null)
      if (user){
        this.user = user
      }
    },
    async getUserList() {
      const { data: res } = await this.$http.get('user/allUser', { params: this.queryInfo });
      if (res.flag == '200') {
        this.userList = res.data;  //用户列表数据
        // console.log(res.data);
        this.total = res.number;  //总记录数
        // console.log(this.total);
      }
    },
    //最大数
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pageNum = val;
      this.getUserList();
    },
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(`user/userState?id=${userInfo.id}&state=${userInfo.state}`);
      if (res.flag != '200') {
        userInfo.state = !userInfo.state;
        return this.$message.error('操作失败！！！');
      }
      this.$message.success('操作成功！！！');
    },
    //监听添加用户
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      let that = this;
      let addData = {
        username: that.addForm.username,
        password: that.addForm.password,
        email: that.addForm.email,
        userUrl: that.imageUrl
      };
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post('user/addUser', addData);
        if (res.flag != '200') {
          return this.$message.error('添加失败');
        }
        this.$message.success('添加成功');
        this.addDialogVisible = false;
        that.getUserList();
      });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.collectNum;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess1(res, file) {
      this.imageUrlU = res.collectNum;
    },
    beforeAvatarUpload1(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    async deleteUser(id) {
      const confirmU = await this.$confirm('此操作将永久删除用户，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warming'
      })
        .catch(err => err);
      if (confirmU != 'confirm') {
        return this.$message.warning('你取消删除！');
      }
      const { data: res } = await this.$http.delete('user/deleteUser?id=' + id);
      if (res.flag != '200') {
        return this.$message.error('删除失败');
      }
      this.$message.success('删除成功');
      this.getUserList();
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('user/getUpdateUser?id=' + id);
      if (res.flag == '200') {
        this.editForm = res.user;
        this.imageUrlU = res.user.userUrl;
        this.editDialogVisible = true;
      }

    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();  //重置信息
    },
    editUser() {
      let that = this;
      let editData = {
        username: that.editForm.username,
        password: that.editForm.password,
        email: that.editForm.email,
        userUrl: that.imageUrlU,
        id: that.editForm.id
      };
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        //发起修改请求
        const { data: res } = await this.$http.post('user/editUser', editData);
        if (res.flag != '200') {
          return this.$message.error('修改失败');
        }
        this.$message.success('修改成功');
        this.editDialogVisible = false;
        this.getUserList();
      });
    },
    handleCommand(command) {

      if (!command) {
        this.$message("菜单选项缺少command属性");
        return;
      }
      switch (command) {
        case "2":
          this.editRole(2)
          break
        case "3":
          this.editRole(3)
          break
      }
    },
    updateId(index){
      this.editRoleId = index
    },
    async editRole(index){
      let that = this
      let RoleData = {
        id: that.editRoleId,
        role: index
      }
      const { data: res } = await this.$http.post('user/editRole',RoleData)
      if (res.flag == "200"){
        this.$message.success('修改成功');
        this.getUserList();
      }else{
        this.$message.error('修改失败');
      }
    }
  }
};
</script>

<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}


::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/*::v-deep .el-upload{*/
/*  border: 1px dashed #d9d9d9;*/
/*  border-radius: 6px;*/
/*}*/
</style>
